<?php
namespace app\index\controller;
use \think\Controller;
use \think\Db;
use app\index\model\VerCode;
use \think\Loader;
use \think\File;
class Set extends Controller
{   
    // 从数据库中取出当前用户资料并加载模版
    public function index()
    {
        $user = Db::table('user')->find(session('uid'));
        return $this->fetch('set',$user);
    }

    //用户设置修改邮箱昵称签名性别
    public function set(){
        $data=input('post.');
        $data['uid']=session('uid');

        $validate = Loader::validate('User');
        if(!$validate->scene('set')->check($data)){
            return ['error'=>1,'info'=>$validate->getError()];
        }
        $res = Db::table('user')->update($data);
        if($res){
            session('username',$data['username']);
            return ['error'=>0,'info'=>'修改成功'];
        }else{
            return ['error'=>1,'info'=>'修改失败'];
        }
    }


    //用户设置修改密码
    public function setPassword(){
        $data = input('post.');

        $validate = Loader::validate('User');
        if(!$validate->scene('setPassword')->check($data)){
            return ['error'=>1,'info'=>$validate->getError()];
        }
        unset($data['repassword']);
        $res = Db::table('user')->where('uid',session('uid'))->update($data);
        if($res){
            return ['error'=>0,'info'=>'修改成功'];
        }else{
            return ['error'=>1,'info'=>'修改失败,请重新输入'];
        }
    }

    //基本设置上传头像
    public function avatarUpload(){

         // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/avatar');
        if($info){
            $savePath='/uploads/avatar/'.$info->getSaveName();
            $res = Db::table('user')->where('uid',session('uid'))->update(['avatar'=>$savePath]);
            if($res){
                $path = ROOT_PATH . 'public' .session('face');
                if (file_exists($path)&&$path<>ROOT_PATH . 'public/static/images/face/336.jpg') {
                    unlink($path);
                }
                session('face',$savePath);
                return ['error=>0','info'=>'上传成功'];
            }else{
                return ['error'=>0,'info'=>'数据没变'];
            }
        }else{
            return ['error'=>1,'info'=>'上传失败'.$file->getError()];
        }
    }



}
